<template>
  <el-container class="container">
    <el-header height="100%">
      <el-form :model="userForm" ref="userForm" label-width="80px" class="form">
        <el-row>
          <el-col :span="6">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="userForm.userName" clearable placeholder="请输入用户名"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="userForm.phone" clearable placeholder="请输入手机号码"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态" prop="status">
              <el-select v-model="userForm.status" clearable placeholder="请选择状态">
                <el-option label="正常" value="0"/>
                <el-option label="停用" value="1"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="创建时间">
              <el-row>
                <el-col :span="11">
                  <el-date-picker v-model="userForm.startTime" type="date" placeholder="开始日期" style="width: 100%;"/>
                </el-col>
                <el-col :span="2" class="line">-</el-col>
                <el-col :span="11">
                  <el-date-picker v-model="userForm.endTime" type="date" placeholder="结束日期" style="width: 100%;"/>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="40px">
              <el-button type="primary" @click="onSubmit" icon="el-icon-search">搜索</el-button>
              <el-button @click="resetForm('userForm')" icon="el-icon-refresh">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="padding-left: 10px">
          <el-button type="primary" plain icon="el-icon-plus" @click="showAddDialog">新增</el-button>
          <el-button type="success" plain icon="el-icon-edit" @click="showModifyDialog()"
                     :disabled="multipleSelection.length !== 1">修改
          </el-button>
          <el-button type="danger" plain icon="el-icon-delete" :disabled="multipleSelection.length === 0"
                     @click="handlerRemove()">删除
          </el-button>
          <el-button type="info" plain icon="el-icon-upload2">导入</el-button>
          <el-button type="warning" plain icon="el-icon-download">导出</el-button>
        </el-row>
      </el-form>
    </el-header>
    <el-main>
      <el-table
        :data="userData"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}"
      >
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          type="index"
          label="编号"
          width="50">
        </el-table-column>
        <el-table-column
          prop="userName"
          label="用户名"
          min-width="120">
        </el-table-column>
        <el-table-column
          prop="phone"
          label="手机号"
          min-width="120">
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          min-width="120">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="0"
              :inactive-value="1"
              @change="toggleStatus(scope)"
              active-color="#13ce66">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          min-width="160">
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          min-width="120">
          <template slot-scope="scope">
            <el-row>
              <el-button type="text" icon="el-icon-edit" @click="showModifyDialog(scope.row.userId)" size="small">修改
              </el-button>
              <el-button type="text" icon="el-icon-delete" size="small" @click="handlerRemove(scope.row.userId)">删除
              </el-button>
            </el-row>
            <el-row>
              <el-button type="text" icon="el-icon-circle-check" @click="showModifyDialog(scope.row.userId)"
                         size="small">分配角色
              </el-button>
              <el-button type="text" icon="el-icon-key" size="small" @click="handlerRemove(scope.row.userId)">重置密码
              </el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-footer height="30px">
      <el-row>
        <el-col :span="24" class="line">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNo"
            :page-sizes="[5, 10 ,15, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </el-col>
      </el-row>
    </el-footer>
    <el-dialog :title="userDialog.title" width="500px" :visible.sync="userDialog.visible">
      <el-form :model="userDialog.form" :rules="userDialog.rules" ref="userDialogForm">
        <el-row>
          <el-col :span="22">
            <el-form-item label="用户名称" :label-width="userDialog.formLabelWidth" prop="userName">
              <el-input v-model="userDialog.form.userName" autocomplete="off" placeholder="请输入用户名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item label="手机号码" :label-width="userDialog.formLabelWidth" prop="phone">
              <el-input v-model="userDialog.form.phone" autocomplete="off" placeholder="请输入手机号码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item label="用户性别" :label-width="userDialog.formLabelWidth" prop="sex">
              <el-select v-model="userDialog.form.sex" placeholder="请选择性别">
                <el-option label="男" :value="1"></el-option>
                <el-option label="女" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item label="状态" :label-width="userDialog.formLabelWidth" prop="status">
              <el-radio-group v-model="userDialog.form.status">
                <el-radio :label="0">正常</el-radio>
                <el-radio :label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item label="备注" :label-width="userDialog.formLabelWidth" prop="remark">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="userDialog.form.remark">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitDialog">确 定</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import userApi from '@/api/system/user';

export default {
  name: 'index',
  data() {
    return {
      userForm: {
        userName: '',
        phone: '',
        status: null,
        startTime: '',
        endTime: '',
      },
      pageNo: 1,
      pageSize: 5,
      total: 0,
      userData: [],
      multipleSelection: [],
      userDialog: {
        visible: false,
        title: '添加用户',
        form: {
          userId: null,
          userName: '',
          phone: '',
          sex: 1,
          status: 0,
          remark: '',
        },
        formLabelWidth: '100px',
        rules: {
          userName: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
            {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'},
          ],
          phone: [
            {required: true, message: '请输入手机号', trigger: 'blur'},
            {min: 11, max: 11, message: '手机号长度为11个字符', trigger: 'blur'},
          ],
        },
      },
    };
  },
  created() {
    this.fetchData(1);
  },
  methods: {
    fetchData(pageNo = this.pageNo, pageSize = this.pageSize, searchObj = this.userForm) {
      userApi.getUserList(pageNo, pageSize, searchObj).then(res => {
        const returnData = res.data;
        this.pageNo = returnData.pageNum;
        this.total = returnData.total;
        this.userData = returnData.list;
      });
    },
    submitDialog() {
      this.$refs.userDialogForm.validate(valid => {
        if (valid) {
          if (this.userDialog.title === '修改用户') {
            this.$confirm('是否确认修改用户信息?', '系统提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }).then(() => {
              this.updateUser('修改成功');
            }).catch(() => {
              this.userDialog.visible = true;
            });
          } else {
            this.updateUser('添加成功');
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    toggleStatus(scope) {
      const msg = scope.row.status === 0 ? '确认要启用名称为[' + scope.row.userName + ']的用户吗？' : '确认要禁用名称为[' +
        scope.row.userName + ']的用户吗？';
      this.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        userApi.updateUser(scope.row).then(() => {
          this.fetchData();
          this.$message({
            type: 'success',
            message: scope.row.status === 0 ? '启用成功' : '禁用成功',
          });
        });
      }).catch(() => {
        scope.row.status = scope.row.status === 0 ? 1 : 0;
      });
    },
    updateUser(msg) {
      userApi.updateUser(this.userDialog.form).then(() => {
        this.userDialog.visible = false;
        this.fetchData();
        this.$message({
          type: 'success',
          message: msg,
        });
      });
    },
    showAddDialog() {
      Object.assign(this.userDialog.form, this.$options.data().userDialog.form);
      this.userDialog.visible = true;
      this.userDialog.title = '添加用户';
    },
    showModifyDialog(id) {
      id = id === undefined ? this.multipleSelection[0].userId : id;
      Object.assign(this.userDialog.form, this.$options.data().userDialog.form);
      this.userDialog.visible = true;
      this.userDialog.title = '修改用户';
      this.userDialog.form.userName = id;
      userApi.getById(id).then(res => {
        this.userDialog.form = res.data;
      });
    },
    onSubmit() {
      this.fetchData(1);
    },
    resetForm(formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields();
        this.userForm.endTime = '';
        this.userForm.startTime = '';
        this.fetchData(1);
      }
    },
    handlerRemove(id) {
      let ids = id == null ? this.multipleSelection.map(t => t.userId) : [id];
      let names = this.multipleSelection.filter(t => ids.includes(t.userId)).map(t => t.userName);
      console.log('names = ' + names);
      this.$confirm('是否删除用户名为"' + names + '"的用户?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        userApi.delBatch(ids).then(res => {
          if (res.data === true) {
            this.fetchData(1);
            this.$message({
              message: '删除成功',
              type: 'success',
            });
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除',
        });
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData(1);
    },
    handleCurrentChange(val) {
      this.pageNo = val;
      this.fetchData();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

  },
};
</script>

<style scoped>
.line {
  text-align: center;
}

.form {
  /*padding-top: 20px;*/
  /*padding-bottom: -15px;*/
}

.container {
  padding: 20px 10px;
}
</style>
